import React, {useEffect} from 'react'
import {Button, Upload, message} from 'antd'
import {PlusCircleOutlined} from '@ant-design/icons'
import {useModel} from 'umi'
import styles from './index.less'
import {uploadFileUrl} from '@/service/common/upload'

const {Dragger} = Upload

const otherUpload = (props: any) => {
	const {fileList, setFileList, enclosureList, urlData, setUrlData} = props
	const {initialState} = useModel('@@initialState')
	const {fileName} = initialState || {}
	useEffect(() => {
		const data = {...urlData}
		fileList?.forEach((item: any, index: number) => {
			if (item?.response) {
				data[`otherDocumentsUrl${index + 1}`] = item?.response?.data?.id
			} else {
				data[`otherDocumentsUrl${index + 1}`] = item?.uid
			}
			setUrlData(data)
		})
		if (fileList?.length === 0) {
			data.otherDocumentsUrl1 = ''
			data.otherDocumentsUrl2 = ''
			data.otherDocumentsUrl3 = ''
		} else if (fileList?.length === 1) {
			data.otherDocumentsUrl2 = ''
			data.otherDocumentsUrl3 = ''
		} else if (fileList?.length === 2) {
			data.otherDocumentsUrl3 = ''
		}
	}, [fileList])
	useEffect(() => {
		const arr: any = []
		enclosureList?.forEach((item: any) => {
			if (item?.targetAttr === 31) {
				arr.push({
					uid: item?.id,
					name: item?.filename,
					url: item?.url,
				})
			}
		})
		setFileList(arr)
	}, [enclosureList])

	const uploadProps = {
		action: uploadFileUrl,
		name: fileName,
		data: {
			modelName: 'spAccess',
			targetAttr: 31,
		},
		fileList,
		beforeUpload: (file: any) => {
			const isLt20M = file.size / 1024 / 1024 < 200
			if (!isLt20M) {
				message.error('文件必须小于200MB')
			}
			return isLt20M
		},
		onChange(info: any) {
			setFileList(info.fileList)
			if (info.file.status === 'done') {
				message.success(info?.file?.response.msg)
			} else if (info.file.status === 'error') {
				message.error(info?.file?.response.msg)
			}
		},
	}
	return (
		<div className={styles.otherUpload}>
			<Dragger {...uploadProps}>
				{fileList?.length < 3 ? (
					<Button type="link" icon={<PlusCircleOutlined />}>
						上传其他文件
					</Button>
				) : (
					''
				)}
			</Dragger>
		</div>
	)
}

export default otherUpload
